import os
from flask import redirect, render_template, url_for, jsonify
from app import cache
from app.tasks.task import restart_uwsgi_sever
from app.views.common import *
from app.views.forms import *
from flask import Blueprint

admin = Blueprint('admin', __name__)


# 首页
@admin.route('/admin/index')
@cache.cached(timeout=60 * 60 * 24, key_prefix=make_cache_key)
def Index():
    returnData = {'title': '后台首页'}
    returnData['total_message_num'] = Message.query.count()  # 留言数
    returnData['total_message_no_num'] = Message.query.filter_by(state=0).count()  # 未处理留言
    returnData['total_blog_num'] = Blog.query.count()  # 博文数
    returnData['total_blog_no_reply_num'] = Reply.query.filter_by(state=0).count()  # 博文评论未处理量
    returnData['total_blog_reply_num'] = Reply.query.count()  # 博文评论量
    returnData['total_loveText_num'] = loveText.query.count()  # 微语量
    returnData['total_category_num'] = Category.query.count()  # 分类量
    returnData['total_photo_num'] = Photos.query.count()  # 微语量
    returnData['total_friend_href_num'] = FriendHref.query.count()  # 友链量
    returnData['monitor'] = getMemCpu()
    returnData = {**returnData, **getData()}
    return render_template('admin/index.html', **returnData)


# 博文列表
@admin.route('/admin/details/list', methods=['POST', 'GET'])
@cache.cached(timeout=60 * 60 * 24 * 100, key_prefix=make_cache_key)
def BlogList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        title = request.form.get('title', '')
        category = request.form.get('category')
        returnData = {'code': 0, 'msg': '', 'data': []}
        blog_query = Blog.query
        if title:
            blog_query = blog_query.filter(Blog.title.like('%' + title + '%'))
        if category:
            blog_query = blog_query.filter(Blog.categoryId == category)
        blog_list = blog_query.order_by(Blog.createTime.desc()).limit(limit).offset(
            (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.id, 'title': item.title, 'readingVolume': item.readingVolume,
             'categoryName': item.categoryInfo.name, 'imgSrc': item.imgSrc, 'createTime': str(item.createTime)} for item
            in blog_list]
        returnData['count'] = blog_query.count()
        return jsonify(returnData)
    categories = Category.query.all()
    return render_template('admin/blog/list.html', title='博文列表', categories=categories)


# CSDN列表
@admin.route('/admin/csdn/list', methods=['POST', 'GET'])
@cache.cached(timeout=60 * 60 * 24 * 100, key_prefix=make_cache_key)
def BlogCSDNList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        title = request.form.get('title', '')
        returnData = {'code': 0, 'msg': '', 'data': []}
        blog_query = CsdnBlog.query
        if title:
            blog_query = blog_query.filter(CsdnBlog.title.like('%' + title + '%'))
        blog_list = blog_query.order_by(CsdnBlog.create_time.desc()).limit(limit).offset(
            (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.id, 'title': item.title, 'href': item.href,
             'tag': item.tag, 'createTime': str(item.create_time)} for item in blog_list]
        returnData['count'] = blog_query.count()
        return jsonify(returnData)
    categories = CsdnBlog.query.with_entities(CsdnBlog.tag).group_by(CsdnBlog.tag).all()
    return render_template('admin/csdn/list.html', title='CSDN博文列表', categories=categories)

# csdn博文插入
@admin.route('/admin/csdn/add', methods=['POST'])
def BlogImport():
    returnData = {'status': 0}
    if request.method == 'POST':
        try:
            csdn_data = CsdnBlog.query.get(request.form.get('Id'))
            blog_info = Blog.query.filter_by(title=csdn_data.title).all()
            if not len(blog_info):
                blog = Blog()
                blog.title = csdn_data.title
                blog.content = csdn_data.content
                blog.categoryid = 1
                blog.imgSrc = 'https://oss.zimu.website/zimu_file/u=269353592,2802096828&fm=26&gp=0.png'
                blog.createTime = datetime.now()
                db.session.add(blog)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*details*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['msg'] = '数据已存在'
        except Exception as e:
            returnData['msg'] = str(e)
    else:
        returnData['msg'] = '请求方式不合理'
    return jsonify(returnData)


# 增加博文
@admin.route('/admin/details/add', methods=['POST', 'GET'])
def BlogAdd():
    forms = BlogForm()
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            try:
                data = forms.data
                blog = Blog()
                blog.title = data['title']
                blog.content = data['content']
                blog.categoryInfo = data['category']
                blog.imgSrc = data['imgSrc']
                blog.createTime = datetime.now()
                db.session.add(blog)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*details*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(["{}:{}".format(k, v[0]) for k, v in forms.errors.items()])
        return jsonify(returnData)
    return render_template('admin/blog/add_edit.html', title='博文新增', form=forms)


# 修改博文
@admin.route('/admin/details/edit/<int:Id>', methods=['POST', 'GET'])
def BlogEdit(Id):
    forms = BlogForm()
    blog = Blog.query.get(Id)
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                blog.title = data['title']
                blog.content = request.form.get('content')
                blog.categoryInfo = data['category']
                blog.imgSrc = data['imgSrc']
                blog.createTime = datetime.now()
                db.session.add(blog)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*details*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.title.errors + forms.content.errors + forms.category.errors)
        return jsonify(returnData)
    content = blog.content
    return render_template('admin/blog/add_edit.html', title='博文修改', blog=blog, form=forms, content=content)


# 删除博文
@admin.route('/admin/details/del')
def BlogDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            blog_obj = Blog.query.get(Id)
            if blog_obj:
                db.session.delete(blog_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*details*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 今日热帖
@admin.route('/admin/blog/hot/list')
def hotBlogList():
    returnData = {'code': 0, 'msg': '', 'data': []}
    page = request.args.get('page', 0)
    limit = request.args.get('limit', 10)
    hot_blog_list = Blog.query.order_by(Blog.createTime.desc()).limit(limit).offset(
        (int(page) - 1) * int(limit)).all()
    if hot_blog_list:
        returnData['data'] = [{'Id': item.id, 'title': item.title, 'readingVolume': item.readingVolume,
                               'categoryName': item.categoryInfo.name} for item in hot_blog_list]
    else:
        returnData['msg'] = '暂无数据'
    returnData['count'] = Blog.query.count()
    return jsonify(returnData)


# 分类列表
@admin.route('/admin/category/list', methods=['POST', 'GET'])
def CategoryList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        returnData = {'code': 0, 'msg': '', 'data': []}
        category_list = Category.query.order_by(Category.id.asc()).limit(limit).offset(
            (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.id, 'name': item.name, 'blogNum': len(item.blogList)} for item in category_list]
        returnData['count'] = Category.query.count()
        return jsonify(returnData)
    return render_template('admin/category/list.html', title='分类列表')


# 增加分类
@admin.route('/admin/category/add', methods=['POST', 'GET'])
def CategoryAdd():
    forms = CategoryForm()
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                category = Category()
                category.name = data['name']
                db.session.add(category)
                db.session.commit()
                returnData['status'] = 1
                r = redis_connect()
                data = r.keys(pattern='*category*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.name.errors)
        return jsonify(returnData)
    return render_template('admin/category/add_edit.html', title='分类新增', form=forms)


# 修改分类
@admin.route('/admin/category/edit/<int:Id>', methods=['POST', 'GET'])
def CategoryEdit(Id):
    forms = CategoryForm()
    category = Category.query.get(Id)
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                category.name = data['name']
                db.session.add(category)
                db.session.commit()
                returnData['status'] = 1
                r = redis_connect()
                data = r.keys(pattern='*category*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.name.errors)
        return jsonify(returnData)
    return render_template('admin/category/add_edit.html', title='分类修改', category=category, form=forms)


# 删除分类
@admin.route('/admin/category/del')
def CategoryDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            category_obj = Category.query.get(Id)
            if category_obj:
                db.session.delete(category_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*category*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 评论列表
@admin.route('/admin/reply/list', methods=['POST', 'GET'])
def ReplyList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        Id = request.form.get('Id')
        nickname = request.form.get('nickname')
        returnData = {'code': 0, 'msg': '', 'data': []}
        ReplyQuery = Reply.query
        if Id:
            reply_list = ReplyQuery.get(Id)
        else:
            if nickname:
                ReplyQuery = ReplyQuery.filter(nickname == nickname)
            reply_list = ReplyQuery.order_by(Reply.createtime.desc()).limit(limit).offset(
                (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.id, 'blogName': item.replyFromBlog.title, 'content': item.content,
             'createTime': str(item.createtime), 'state': item.state, 'userName': item.nickname} for item in reply_list]
        returnData['count'] = Blog.query.count()
        return jsonify(returnData)
    return render_template('admin/reply/list.html', title='评论列表')


# 回复评论
@admin.route('/admin/reply/reply/<int:Id>', methods=['POST', 'GET'])
def ReplyToReply(Id):
    try:
        forms = ReplyForm()
        replyObj = Reply.query.get(Id)
        forms.replyContent.data = replyObj.replyContent
        if request.method == 'POST':
            returnData = {'status': 0}
            if forms.validate_on_submit():
                data = forms.data
                try:
                    replyObj.replyContent = data['replyContent']
                    replyObj.state = 1
                    db.session.add(replyObj)
                    db.session.commit()
                    returnData['status'] = 1
                    r = redis_connect()
                    data = r.keys(pattern='*reply*')
                    if data:
                        r.delete(*data)
                    returnData['status'] = 1
                except Exception as e:
                    returnData['msg'] = str(e)
            else:
                returnData['msg'] = ','.join(forms.replyContent.errors)
            return jsonify(returnData)
        return render_template('admin/reply/reply.html', Reply=replyObj, form=forms, title='回复评论')
    except Exception as e:
        return redirect(url_for('admin.Index'))


# 删除评论
@admin.route('/admin/reply/del')
def ReplyDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            reply_obj = Reply.query.get(Id)
            if reply_obj:
                db.session.delete(reply_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*reply*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 最新评论
@admin.route('/admin/reply/new/list')
def newReplyList():
    returnData = {'code': 0, 'msg': '', 'data': []}
    page = request.args.get('page', 0)
    limit = request.args.get('limit', 10)
    new_reply_list = Reply.query.filter_by(state=0).limit(limit).offset((int(page) - 1) * int(limit)).all()
    if new_reply_list:
        returnData['data'] = [{'Id': item.id, 'content': item.content, 'blogName': item.replyFromBlog.title,
                               'createTime': str(item.createTime), 'state': item.state, 'userName': item.nickname} for
                              item in new_reply_list]
    else:
        returnData['msg'] = '暂无数据'
    returnData['count'] = Reply.query.count()
    return jsonify(returnData)


# 微语列表
@admin.route('/admin/whisper/list', methods=['POST', 'GET'])
def LoveTextList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        search = request.form.get('content', '')
        returnData = {'code': 0, 'msg': '', 'data': []}
        LoveTextQuery = loveText.query
        if search:
            LoveTextQuery = LoveTextQuery.filter(loveText.content.like('%' + search + '%'))
        love_text_list = LoveTextQuery.order_by(loveText.id.asc()).limit(limit).offset(
            (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.id, 'content': item.content, 'praisePoints': item.praisePoints,
             'createTime': str(item.createTime)} for item in love_text_list]
        returnData['count'] = LoveTextQuery.count()
        return jsonify(returnData)
    return render_template('admin/whisper/list.html', title='微语列表')


# 增加微语
@admin.route('/admin/whisper/add', methods=['POST', 'GET'])
def WhisperAdd():
    forms = WhisperForm()
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                whisper = loveText()
                whisper.content = data['Content']
                whisper.createTime = datetime.now()
                db.session.add(whisper)
                db.session.commit()
                returnData['status'] = 1
                r = redis_connect()
                data = r.keys(pattern='*whisper*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.Content.errors)
        return jsonify(returnData)
    return render_template('admin/whisper/add_edit.html', title='微语新增', form=forms)


# 修改微语
@admin.route('/admin/whisper/edit/<int:Id>', methods=['POST', 'GET'])
def WhisperEdit(Id):
    forms = WhisperForm()
    whisper = loveText.query.get(Id)
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                whisper.content = data['content']
                db.session.add(whisper)
                db.session.commit()
                returnData['status'] = 1
                r = redis_connect()
                data = r.keys(pattern='*whisper*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.Content.errors)
        return jsonify(returnData)
    forms.Content.data = whisper.content
    return render_template('admin/whisper/add_edit.html', title='微语修改', whisper=whisper, form=forms)


# 删除微语
@admin.route('/admin/whisper/del')
def WhisperDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            whisper_obj = loveText.query.get(Id)
            if whisper_obj:
                db.session.delete(whisper_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*whisper*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 留言列表
@admin.route('/admin/leacots/list', methods=['GET', 'POST'])
def MessageList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        nickname = request.form.get('nickname')
        returnData = {'code': 0, 'msg': '', 'data': []}
        MessageQuery = Message.query
        if nickname:
            MessageQuery = MessageQuery.filter(nickname == nickname)
        message_list = MessageQuery.order_by(Message.Id.asc()).limit(limit).offset((int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.Id, 'content': item.content, 'state': item.state,
             'userName': item.nickname, 'createTime': str(item.createtime)} for item in message_list]
        returnData['count'] = MessageQuery.count()
        return jsonify(returnData)
    return render_template('admin/message/list.html', title='留言列表')


# 回复评论
@admin.route('/admin/leacots/reply/<int:Id>', methods=['POST', 'GET'])
def MessageToReply(Id):
    forms = MessageForm()
    message_obj = Message.query.get(Id)
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                message_obj.replyContent = data['replyContent']
                message_obj.state = 1
                db.session.add(message_obj)
                db.session.commit()
                returnData['status'] = 1
                r = redis_connect()
                data = r.keys(pattern='*leacots*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.replyContent.errors)
        return jsonify(returnData)
    forms.replyContent.data = message_obj.replyContent
    return render_template('admin/message/reply.html', Message=message_obj, form=forms, title='回复留言')


# 删除留言
@admin.route('/admin/leacots/del')
def MessageDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            message_obj = Message.query.get(Id)
            if message_obj:
                db.session.delete(message_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*leacots*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 相册列表
@admin.route('/admin/album/list', methods=['POST', 'GET'])
def PhotoList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        returnData = {'code': 0, 'msg': '', 'data': []}
        PhotosQuery = Photos.query
        photo_list = PhotosQuery.order_by(Photos.id.asc()).limit(limit).offset((int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.id, 'imgSrc': item.imgSrc,
             'imgName': item.imgName, 'createTime': str(item.createTime)} for item in photo_list]
        returnData['count'] = PhotosQuery.count()
        return jsonify(returnData)
    return render_template('admin/photo/list.html', title='相册列表')


# 增加相片
@admin.route('/admin/album/add', methods=['POST', 'GET'])
def PhotoAdd():
    forms = PhotoForm()
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                photo = Photos()
                photo.imgName = data['imgName']
                photo.imgSrc = data['imgSrc']
                photo.createTime = datetime.now()
                db.session.add(photo)
                db.session.commit()
                returnData['status'] = 1
                r = redis_connect()
                data = r.keys(pattern='*album*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.Content.errors)
        return jsonify(returnData)
    return render_template('admin/photo/add_edit.html', title='相片新增', form=forms)


# 修改相片
@admin.route('/admin/album/edit/<int:Id>', methods=['POST', 'GET'])
def PhotoEdit(Id):
    forms = PhotoForm()
    photo = Photos.query.get(Id)
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                photo.imgName = data['imgName']
                photo.imgSrc = data['imgSrc']
                db.session.add(photo)
                db.session.commit()
                returnData['status'] = 1
                r = redis_connect()
                data = r.keys(pattern='*album*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.imgName.errors + forms.imgSrc.errors)
        return jsonify(returnData)
    forms.imgName.data = photo.imgName
    forms.imgSrc.data = photo.imgSrc
    return render_template('admin/photo/add_edit.html', title='相片修改', photo=photo, form=forms)


# 删除微语
@admin.route('/admin/album/del')
def PhotoDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            photo_obj = Photos.query.get(Id)
            if photo_obj:
                db.session.delete(photo_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*album*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 系统设置
@admin.route('/admin/system', methods=['POST', 'GET'])
def SystemInfo():
    config = current_app.config
    if request.method == 'POST':
        data = request.form
        returnData = {'status': 0}
        if data['type'] == 'system':
            try:
                for key, value in data.items():
                    if key != 'type' and key != 'file' and value:
                        systemObj = System.query.filter_by(key=key).first()
                        systemObj.value = value
                        db.session.add(systemObj)
                db.session.commit()
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        elif data['type'] == 'config':
            try:
                for key, value in data.items():
                    if key != 'type' and key != 'file' and value:
                        config[key.upper()] = value
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        elif data['type'] == 'pid':
            returnData = {'code': 0, 'msg': ''}
            returnData['data'] = [{'Proto': row.split()[0], 'Recv-Q': row.split()[1], 'Send-Q': row.split()[2],
                                   'Local_Address': row.split()[3], 'Foreign_Address': row.split()[4],
                                   'State': row.split()[5], 'PID/Program name': row.split()[6]} for row in
                                  os.popen('sudo netstat -apn | grep 127.0.0.1:506[0-2] | grep uwsgi').readlines()]
            returnData['count'] = len(returnData['data'])
        elif data['type'] == 'celery':
            returnData = {'status': 0}
            returnData['data'] = os.popen('celery -A celery_worker.app status').read()
        else:
            returnData['msg'] = '请求模式不正确'
        return jsonify(returnData)
    else:
        email_dict = {}
        celery_dict = {}
        cache_dict = {}
        for key, value in config.items():
            key = key.lower()
            if 'mail' in key:
                email_dict[key] = value
            elif 'celery' in key:
                celery_dict[key] = value
            elif 'cache' in key:
                cache_dict[key] = value
        return render_template('admin/system/system.html', title='系统设置', email_dict=email_dict, celery_dict=celery_dict,
                               cache_dict=cache_dict)


# 关于我设置
@admin.route('/admin/aboutme', methods=['POST', 'GET'])
def AboutMe():
    if request.method == 'POST':
        returnData = {'status': 0}
        try:
            data = request.form
            for key, value in data.items():
                if key != 'file':
                    systemObj = System.query.filter_by(key=key).first()
                    systemObj.value = value
                    db.session.add(systemObj)
            db.session.commit()
            returnData['status'] = 1
        except Exception as e:
            returnData['msg'] = str(e)
        return jsonify(returnData)
    about_list = System.query.filter(System.key.like('aboutme_%')).all()
    return render_template('admin/system/about_me.html', title='系统设置', aboutMe=about_list)


# 技能列表
@admin.route('/admin/tool/list', methods=['POST'])
def ToolList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        returnData = {'code': 0, 'msg': '', 'data': []}
        toolQuery = Tool.query
        tool_list = toolQuery.limit(limit).offset((int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.id, 'toolImgSrc': item.toolImgSrc, 'percent': item.percent} for item in tool_list]
        returnData['count'] = toolQuery.count()
        return jsonify(returnData)


# 增加技能
@admin.route('/admin/tool/add', methods=['POST', 'GET'])
def ToolAdd():
    forms = ToolForm()
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                tool_obj = Tool()
                tool_obj.toolImgSrc = data['toolImgSrc']
                tool_obj.percent = data['percent']
                db.session.add(tool_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*tool*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.name.errors)
        return jsonify(returnData)
    return render_template('admin/system/add_edit_tool.html', title='技能新增', form=forms)


# 修改技能
@admin.route('/admin/tool/edit/<int:Id>', methods=['POST', 'GET'])
def ToolEdit(Id):
    forms = ToolForm()
    tool_obj = Tool.query.get(Id)
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                tool_obj.toolImgSrc = data['toolImgSrc']
                tool_obj.percent = data['percent']
                db.session.add(tool_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*tool*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.name.errors)
        return jsonify(returnData)
    forms.toolImgSrc.data = tool_obj.toolImgSrc
    forms.percent.data = tool_obj.percent
    return render_template('admin/system/add_edit_tool.html', title='技能修改', tool_obj=tool_obj, form=forms)


# 删除分类
@admin.route('/admin/tool/del')
def ToolDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id',0)
        if Id:
            tool_obj = Tool.query.get(Id)
            if tool_obj:
                db.session.delete(tool_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*tool*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 系统监控
@admin.route('/admin/monitor')
def Monitor():
    returnData = {'title': '系统监控'}
    # PV、UV
    returnData['history_pv_uv_line_label'] = history_is_traffic_trends()
    returnData['pv_uv_line_label'] = today_is_traffic_trends()
    # TOP5 IP榜单
    returnData['top5_ip_bar'] = top5_ip_list()
    # 浏览器分布
    returnData['brower_pie'] = visitor_browser_distribution()
    # 操作系统分布
    returnData['system_pie'] = system_distribution()
    # 中国城市分布
    returnData['ipaddress_map'] = ipaddress_distribution()
    return render_template('admin/monitor/index.html', **returnData)


# 登陆
@admin.route('/admin/login', methods=['GET', 'POST'])
def Login():
    referer = request.args.get('referer')
    forms = AdminLoginForm()
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data  # 获取form数据信息
            if data['username'] != 'modu_zimu':
                returnData['info'] = "账号不存在"
            elif data['password'] != 'FanYan879688':
                returnData['info'] = "密码错误"
            else:
                session['admin_check'] = True
                returnData['status'] = 1
                returnData['go'] = referer
                returnData['redirect'] = referer if referer else url_for('admin.Index')  # 重定向到首页
        else:
            returnData['info'] = ','.join(forms.username.errors + forms.password.errors + forms.errors)
        return jsonify(returnData)
    return render_template('admin/login.html', form=forms, title='登录', referer=referer)


# 登出
@admin.route('/admin/logout')
def Logout():
    session.clear()
    return redirect(url_for('admin.Login'))


# 验证登录
@admin.before_request
def AdminBeforeRequest():
    path = request.url
    if 'admin' in path:
        # 判断是否登录
        if 'admin_check' in session and session['admin_check']:
            pass
        # 未登录，判断请求地址，是否是默认地址
        else:
            if 'login' not in path and 'captcha' not in path and 'logout' not in path:
                return redirect(url_for('admin.Login', referer=request.path))
            else:
                pass
    else:
        pass


# 实时CPU和内存情况
@admin.route('/monitor/info')
def MonitorInfo():
    return jsonify(getMemCpu())


# 实时数据监控
@admin.route('/monitor/user/info')
def MonitorUserInfo():
    return jsonify(getData())


# 全局模板数据
@admin.app_context_processor
def main_commont():
    system_list = System.query.filter(System.key.like('common_%')).all()
    system_dict = {item.key: item.value for item in system_list}
    friend_href_list = FriendHref.query.all()
    system_dict['friend_href_list'] = [
        {'title': item.title, 'href': item.href} for item in friend_href_list]
    return system_dict


# 重启服务
@admin.route('/restart/server')
def RestartSever():
    returnData = {'status': 0}
    # 执行重启uwsgi任务
    restart_uwsgi_sever.delay()
    returnData['msg'] = os.popen('pwd').read()
    return jsonify(returnData)


# 重启Celery服务
@admin.route('/restart/celery')
def RestartCelery():
    returnData = {'status': 0}
    returnData['msg'] = os.popen(
        'sudo /vdc/anaconda3/bin/celery multi restart -A celery_worker.app zimu -l INFO --logfile=log/celery_zimu.log').read()
    return jsonify(returnData)


# 模型列表
@admin.route('/admin/model/add', methods=['POST', 'GET'])
def ModelAdd():
    forms = SystemForm()
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                system = System()
                system.key = data['key']
                system.content = data['content']
                system.type = data['type']
                db.session.add(system)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*about*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.key.errors + forms.type.errors + forms.content.errors)
        return jsonify(returnData)
    return render_template('admin/model/add_edit.html', title='模型添加', form=forms)


# 删除关于我字段
@admin.route('/admin/model/del')
def ModelDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            system_obj = System.query.get(Id)
            if system_obj:
                db.session.delete(system_obj)
                db.session.commit()
                r = redis_connect()
                data = r.keys(pattern='*about*')
                if data:
                    r.delete(*data)
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 友情链接列表
@admin.route('/admin/friend/href/list', methods=['POST', 'GET'])
def FriendHrefList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        returnData = {'code': 0, 'msg': '', 'data': []}
        friend_href_list = FriendHref.query.order_by(FriendHref.id.asc()).limit(limit).offset(
            (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.id, 'title': item.title, 'href': item.href, 'createTime': str(item.createTime),
             'upgradeTime': str(item.upgradeTime)} for item in friend_href_list]
        returnData['count'] = FriendHref.query.count()
        return jsonify(returnData)
    return render_template('admin/system/friend_href.html', title='友链列表')


# 增加友链
@admin.route('/admin/friend/href/add', methods=['POST', 'GET'])
def FriendHrefAdd():
    forms = FriendHrefForm()
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                friend_href_obj = FriendHref()
                friend_href_obj.title = data['title']
                friend_href_obj.href = data['href']
                friend_href_obj.createTime = datetime.now()
                db.session.add(friend_href_obj)
                db.session.commit()
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.name.errors)
        return jsonify(returnData)
    return render_template('admin/system/add_edit_friend_href.html', title='友链新增', form=forms)


# 修改友链
@admin.route('/admin/friend/href/edit/<int:Id>', methods=['POST', 'GET'])
def FriendHrefEdit(Id):
    forms = FriendHrefForm()
    friend_href_obj = FriendHref.query.get(Id)
    if request.method == 'POST':
        returnData = {'status': 0}
        if forms.validate_on_submit():
            data = forms.data
            try:
                friend_href_obj.title = data['title']
                friend_href_obj.href = data['href']
                friend_href_obj.upgradeTime = datetime.now()
                db.session.add(friend_href_obj)
                db.session.commit()
                returnData['status'] = 1
            except Exception as e:
                returnData['msg'] = str(e)
        else:
            returnData['msg'] = ','.join(forms.name.errors)
        return jsonify(returnData)
    forms.title.data = friend_href_obj.title
    forms.href.data = friend_href_obj.href
    return render_template('admin/system/add_edit_friend_href.html', title='友链修改', friend_href_obj=friend_href_obj,
                           form=forms)


# 删除分类
@admin.route('/admin/friend/href/del')
def FriendHrefDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            friend_href_obj = FriendHref.query.get(Id)
            if friend_href_obj:
                db.session.delete(friend_href_obj)
                db.session.commit()
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 网站地图
@admin.route('/admin/sitemap/list', methods=['POST', 'GET'])
def SiteMapList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        returnData = {'code': 0, 'msg': '', 'data': []}
        sitemap_list = SiteMap.query.order_by(SiteMap.Id.asc()).limit(limit).offset((int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.Id, 'loc': item.loc, 'priority': item.priority, 'lastmod': str(item.lastmod),
             'changefreq': item.changefreq} for item in sitemap_list]
        returnData['count'] = SiteMap.query.count()
        return jsonify(returnData)
    return render_template('admin/system/sitemap.html', title='网站地图列表')


# 删除网站地图
@admin.route('/admin/sitemap/del')
def SiteMapDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id', 0)
        if Id:
            sitemap_obj = SiteMap.query.get(Id)
            if sitemap_obj:
                db.session.delete(sitemap_obj)
                db.session.commit()
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)


# 推广
@admin.route('/admin/promotion/list', methods=['POST', 'GET'])
def PromotionList():
    if request.method == 'POST':
        page = request.form.get('page', 0)
        limit = request.form.get('limit', 10)
        returnData = {'code': 0, 'msg': '', 'data': []}
        promotion_list = Promotion.query.order_by(Promotion.Id.asc()).limit(limit).offset(
            (int(page) - 1) * int(limit)).all()
        returnData['data'] = [
            {'Id': item.Id, 'name': item.name, 'title': item.title, 'by_friend': item.by_friend, 'by_me': item.by_me,
             'href': item.href, 'startTime': str(item.startTime), 'endTime': str(item.endTime)} for item in
            promotion_list]
        returnData['count'] = Promotion.query.count()
        return jsonify(returnData)
    return render_template('admin/system/promotion.html', title='推广列表')


# 删除推广
@admin.route('/admin/promotion/del')
def PromotionDel():
    returnData = {'status': 0}
    try:
        Id = request.args.get('Id',0)
        if Id:
            promotion_obj = Promotion.query.get(Id)
            if promotion_obj:
                db.session.delete(promotion_obj)
                db.session.commit()
                returnData['status'] = 1
            else:
                returnData['error'] = 'ID 不存在'
        else:
            returnData['error'] = 'ID 异常'
    except Exception as e:
        returnData['error'] = str(e)
        db.session.rollback()
        current_app.logger.error(request.path + ',' + str(e))
    return jsonify(returnData)
